<?php


namespace app\common\caches;


use app\common\models\LoveDiary;
use Carbon\Carbon;
use think\facade\Cache;

class DiaryCache
{
    public static function set(LoveDiary $diary)
    {
        return Cache::store('redis')->handler()->hset("user:{$diary->user_id}.diary", "diary:{$diary->id}", serialize($diary));
    }

    public static function get(int $user_id, int $diary_id)
    {
        $diary = Cache::store('redis')->handler()->hget("user:{$user_id}.diary", "diary:{$diary_id}");
        return unserialize($diary);
    }

    public static function del(LoveDiary $diary)
    {
        return Cache::store('redis')->handler()->hdel("user:{$diary->user_id}.diary", "diary:{$diary->id}");
    }

    public static function setCreateDate(int $user_id)
    {
        return Cache::store('redis')->handler()->hset("diary.create.date", "user:{$user_id}", Carbon::now()->format('Y-m-d'));
    }

    public static function getCreateDate(int $user_id)
    {
        return Cache::store('redis')->handler()->hget("diary.create.date", "user:{$user_id}");
    }

    public static function setFetchList(int $user_id, array $params, $data)
    {
        ksort($params);
        $redis_key = md5($user_id . implode('',array_values($params)));
        return Cache::tag("user:{$user_id}.diary.query")->set("diaries:{$redis_key}", $data, 60*60*24);
    }

    public static function getFetchList(int $user_id, array $params)
    {
        ksort($params);
        $redis_key = md5($user_id . implode('',array_values($params)));
        return Cache::get("diaries:{$redis_key}");
    }

    public static function setMonthCount(int $user_id, string $month, $data)
    {
        return Cache::tag("user:{$user_id}.diary.query")->set("user:{$user_id}.month:{$month}.diary_count", $data, 60*60);
    }

    public static function getMonthCount(int $user_id, string $month)
    {
        return Cache::get("user:{$user_id}.month:{$month}.diary_count");
    }

    // 移除查询结果
    public static function removeQueryData(int $user_id)
    {
        return Cache::tag("user:{$user_id}.diary.query")->clear();
    }
}
